package com.bnq.logc.utils

import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothGattCallback
import android.bluetooth.BluetoothGattCharacteristic
import android.bluetooth.BluetoothProfile
import android.content.Context
import android.content.Intent
import androidx.fragment.app.Fragment
import java.io.File
import java.util.UUID
import kotlin.concurrent.thread


object BluetoothUtil {

    val MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB")

    fun getBluetoothAdapter(): BluetoothAdapter? {
        return BluetoothAdapter.getDefaultAdapter()
    }

    fun getPairedDevices(): Set<BluetoothDevice>? {
        val adapter = getBluetoothAdapter()
        return adapter?.bondedDevices
    }

    fun openBluetooth(fragment:Fragment,requestCode:Int) {
        fragment.startActivityForResult(Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), requestCode)
    }

    fun sendFile(context: Context,file:File,address:String,resultFun:(Boolean)->Unit){
        val adapter = getBluetoothAdapter()
        if(adapter != null && adapter.isEnabled){
            val device = adapter.getRemoteDevice(address)
            val socket = device.createRfcommSocketToServiceRecord(MY_UUID)
            thread {
                try{
                    socket.connect()
                    val outputStream = socket.outputStream
                    val fileStream = file.inputStream()
                    val buffer = ByteArray(1024)
                    var len = fileStream.read(buffer)
                    while (len != -1){
                        outputStream.write(buffer,0,len)
                        len = fileStream.read(buffer)
                    }
                    outputStream.close()
                    fileStream.close()
                    socket.close()
                    resultFun(true)

                }catch (e:Exception){
                    e.printStackTrace()
                    resultFun(false)
                }
            }
        }else{
            resultFun(false)
        }
    }

    fun bluetoothSendFile2(context: Context,file: File,requestCode: Int){
        /*if(ContextCompat.checkSelfPermission(requireActivity(),
                Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(requireActivity(),
                    Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(requireActivity(),
                    Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                showToast("请先授予蓝牙权限")
                return@CommonItem
            }
            if(BluetoothUtil.getBluetoothAdapter() == null){
                showToast("当前设备不支持蓝牙")
                return@CommonItem
            }
            val devices = BluetoothUtil.getPairedDevices()
            if(devices.isNullOrEmpty()){
                showToast("当前设备没有配对的蓝牙设备，请先到系统设置中配对蓝牙设备")
                return@CommonItem
            }
            val deviceItems = devices.map { AlertDialogUtil.Companion.CommonItem(0,it.name,it){ dialog,item->dialog.dismiss()
                val device = item.tag as BluetoothDevice
                BluetoothUtil.sendFile(requireContext(),file,device.address){
                    if(it){
                        showToast("发送成功")
                    }else{
                        showToast("发送失败")
                    }
                }
            }}
            AlertDialogUtil.showCommonListDialog(requireContext(),deviceItems.toTypedArray())*/
    }

    fun bluetoothSendFile(fragment: Fragment,file: File,requestCode: Int){
        val intent = Intent()
        intent.action = Intent.ACTION_SEND
        intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION
        FileUtil.getUriForFile(fragment.requireContext(),file)?.let {
            intent.putExtra(Intent.EXTRA_STREAM,it)
            intent.type = "application/octet-stream"
            //intent.setPackage("com.android.bluetooth")
            fragment.startActivityForResult(Intent.createChooser(intent,"选择应用"),requestCode)
        }
    }

}